package cn.springcloud.fix.common.core.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Component
@WebFilter(urlPatterns = "/*", filterName = "userContextFilter")
public class UserContextFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String id = request.getHeader(UserContext.ID_HEADER_KEY);
        if (id == null || id.trim().length() == 0) {
            UserContextHolder.remove();
        } else {
            UserContext context = new UserContext();
            context.id = id;
            UserContextHolder.setContext(context);
            log.info("当前入栈id:{}", id);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
